import React, { useMemo, useState } from 'react'

export default function Umemo() {
    /**
     * useMemo返回的是一个值，useCallback返回的是回调函数本身
     * useMemo缓存计算结果，useCallback缓存函数引用
     * useMemo适用于排序、过滤大量数据等，useCallback适用于需要传递给子组件的回调函数
     */
    const [str, setStr] = useState('str')
    const [goods, setGoods] = useState([
        { id: 1, name: '苹果', price: 10, count: 1 },
        { id: 2, name: '荔枝', price: 15, count: 1 },
        { id: 3, name: '草莓', price: 16, count: 1 }
    ])
    const addcount = (id) => {
        setGoods(goods.map(i => i.id === id?{...i, count: i.count+1}: i))
    }
    const subcount = (id) => {
        setGoods(goods.map(i => i.id === id?{...i, count: i.count-1}: i))
    }

    // 不使用useMemo，是一个方法
    const total = () => {
        console.log('total')
        return goods.reduce((total, i) => total+i.price*i.count,0)
    }

    // 使用useMemo，不是一个方法
    // const total = useMemo(() => {
    //     console.log('total')
    //     return goods.reduce((total, i) => total+i.price*i.count,0)
    // }, [goods])
  return (
    <div>
        <input type="text" value={str} onChange={e => setStr(e.target.value)} />
        <table>
            <tr>
                <td>名称</td>
                <td>价格</td>
                <td>数量</td>
            </tr>
            {
                goods.map(i => {
                    return <tr>
                        <td>{i.name}</td>
                        <td>￥{i.price}</td>
                        <td>
                            <button onClick={() => addcount(i.id)}>+</button>
                            <span>{i.count}</span>
                            <button onClick={() => subcount(i.id)}>-</button>
                        </td>
                    </tr>
                })
            }
        </table>
        <div>总价：{total()}</div>
        {/* <div>总价：{total}</div> */}
    </div>
  )
}
